﻿@using Huirui.Cavan.Domain.MainBoundedContext.PurchaseModule
@model Huirui.Cavan.Presentation.ViewModel.PurchaseModule.IPurchaseReturnViewModel
@{
    Layout = null;
}
@using (Html.BeginForm(ActionConst.ADD, ControllerConst.PURCHASERETURN))
{
    <div class="tool_bar">
        <input id="purchretrun_save" type="submit" style="display: none;" />
        <input id="purchreturn_reset" type="reset" style="display: none" />
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-save'"
            onclick="javascript:$('#purchretrun_save').click()">保存</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add'">新增</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-ok'" onclick="openWindow('selectStockWindowFromPurchase')">按入库单退货</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-delete'">删除</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'" onclick="addTab('退货列表','center_tt','@Url.Action(ActionConst.LIST, ControllerConst.PURCHASERETURN)')">查询</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-print'">打印</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-collapse'"
            onclick="toggleHeard()">折叠/展开</a>
    </div>
    
    <table class="form_heard">
        <tr>
            <td class="c100">
                <label>
                    退货日期:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.ReturnDate, new { id = "returnDate", style = "height:18px", @class = "Wdate", onfocus = "WdatePicker({minDate:'%y-%M-#{%d+1}'})" })
            </td>
            <td class="c100">
                <label>
                    采购人员:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.PurchaseEmployee.Id, new { id = "purchaseEmployeeCodeForPurchaseReturn" })
                @Html.HiddenFor(m => m.Item.PurchaseEmployee.Name, new { id = "purchaseEmployeeNameForPurchaseReturn" })
            </td>
            <td class="c100">
                <label>
                    退货单号:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Id, new { id = "code" })
            </td>
            <td class="c10"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    供应商:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Supplier.Id, new { id = "supplierCodeForPurchaseReturn" })
            </td>
            <td colspan="2">
                @Html.TextBoxFor(m => m.Item.Supplier.Name, new { id = "supplierNameForPurchaseReturn", @class = "withprompt", @Value = "显示供应商名称" })
            </td>
            <td class="c100">
                <label>
                    供应商票据号:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.SupplierInvoiceNumber, new { id = "supplierInvoiceNumber" })
            </td>
            <td class="c10"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    币别:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Currency, new { id = "currency" })
            </td>
            <td class="c100">
                <label>
                    汇率:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.CurrencyRate, new { id = "currencyRate" })
            </td>
            <td class="c100">
                <label>
                    税率:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.TaxRate, new { id = "taxRate" })
            </td>
            <td class="c10">
                @Html.Raw("%")
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    仓库:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.WareHouse.Address, new { id = "wareHouseAddressForPurchaseReturn" })
                @Html.HiddenFor(m => m.Item.WareHouse.Id, new { id = "wareHouseCodeForPurchaseReturn" })
            </td>
            <td class="c100">
                <label>
                    联系人:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Contact, new { id = "contact" })
            </td>
            <td class="c100">
                <label>
                    电话:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.ContactTelephone, new { id = "contactTelephone" })
            </td>
            <td class="c10"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    送货地址:</label>
            </td>
            <td colspan="4">
                @Html.TextBoxFor(m => m.Item.DeliveryAddress, new { id = "address" })
            </td>
            <td colspan="2">
                <a>请选择常用送货地址</a>
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    备注:</label>
            </td>
            <td colspan="4">
                @Html.TextBoxFor(m => m.Item.Remark, new { id = "remark" })
            </td>
            <td colspan="2">
                <a>请选择常用备注</a>
            </td>
        </tr>
    </table>
    @Html.HiddenFor(m => m.StockInOutDetails, new { id = "stockInOutDetailsForPurchaseReturn" })
    @Html.HiddenFor(m => m.Purchases, new { id = "purchases" })
}
<table id="selectedStocksForPurchaseReturn" title="存货列表" toolbar="#purchreturn_tb">
    <tfoot>
        <tr>
            <td class="col_5">合计
            </td>
            <td class="col_10">&nbsp;
            </td>
            <td class="col_10">&nbsp;
            </td>
            <td class="col_10">&nbsp;
            </td>
            <td class="col_10">求和
            </td>
            <td class="col_10">&nbsp;
            </td>
            <td class="col_10">求和
            </td>
            <td class="col_10">求和
            </td>
            <td class="col_10">&nbsp; 求和
            </td>
            <td class="col_5"></td>
            <td class="col_5"></td>
            <td class="col_10"></td>
        </tr>
    </tfoot>
</table>
<div id="purchreturn_tb">
    <a href="#" id="selectStockForPurchaseReturn" class="easyui-linkbutton" iconcls="icon-checked"
        plain="true" onclick="InitSelectStock('stocksForPurchaseReturn');openWindow('selectStockWindowForPurchaseReturn')">选择商品</a>
    <a href="#" id="batchDeleteForPurchaseReturn" class="easyui-linkbutton" iconcls="icon-delete"
        plain="true">批量删行</a>
</div>

@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.STOCK, new { purpose = "ForPurchaseReturn" }); }
@{ Html.RenderAction(ActionConst.STOCKSFROMPURCHASE, ControllerConst.STOCK); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.SUPPLIER, new { purpose = "ForPurchaseReturn" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.WAREHOUSE, new { purpose = "ForPurchaseReturn" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.EMPLOYEE, new { purpose = "ForPurchaseReturn" }); }

<script type="text/javascript">
    $(function () {
        $('#selectedStocksForPurchaseReturn').datagrid({
            columns: [[
                { field: 'NoPrefixId', title: '存货编码', width: 100 },
                { field: 'Id', title: '存货编码', width: 100, hidden: true },
                { field: 'Name', title: '存货名称', width: 80 },
                { field: 'Specification', title: '规格', width: 60 },
                { field: 'Number', title: '数量', width: 100, editor: { type: 'numberbox' } },
                { field: 'StandardPurchasePrice', title: '单价', width: 100, editor: { type: 'numberbox' } },
                { field: 'PurchaseAmount', title: '采购额', width: 80 },
                { field: 'TaxAmount', title: '税额', width: 80 },
                { field: 'Cost', title: '成本额', width: 80 },
                { field: 'UnitCost', title: '单位成本', width: 80 },
                { field: 'PurchaseCode', title: '采购单号', width: 80 },
                { field: 'Remark', title: '备注', width: 80 }
            ]]
        });

        $("#searchStockForPurchaseReturn").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#stocksForPurchaseReturn').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectStockForPurchaseReturn").bind("click", function () {
            $('#selectedStocksForPurchaseReturn').datagrid('loadData', { total: 0, rows: [] });
            var rows = $('#stocks').datagrid('getRows');
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].IsSelected = true) {
                    insert(rows[i].NoPrefixId, rows[i].Id, rows[i].Name, rows[i].Specification, 0, rows[i].UnitCost, 0, 0, 0, 0, $("#purchaseCode").val(), 'test');
                }
            }
        });

        $("#doSelectStocksFromPurchase").bind("click", function () {
            $('#selectedStocksForPurchaseReturn').datagrid('loadData', { total: 0, rows: [] });
            var rows = $('#stocksFromPurchase').datagrid('getSelections');
            for (var i = 0; i < rows.length; i++) {
                $('#stocksFromPurchase').datagrid('endEdit', i);
                insert(rows[i].NoPrefixId, rows[i].Code, rows[i].Name, rows[i].Specification, rows[i].ReturnNumber, rows[i].UnitCost, 0, 0, 0, 0, rows[i].PurchaseCode, 'test');
            }
            closeWindow("selectStockWindowFromPurchase");
        });

        function insert(noPrefixId, id, name, specification, number, standardPurchasePrice, purchaseAmount, taxAmount, cost, unitCost, purchaseCode, remark) {
            var rows = $('#selectedStocksForPurchaseReturn').datagrid('getRows');
            index = -1;
            if (rows.length == 0) {
                index = 0;
            }
            else {
                index = rows.length;
            }

            $('#selectedStocksForPurchaseReturn').datagrid('insertRow', {
                index: index,
                row: {
                    NoPrefixId: noPrefixId,
                    Id: id,
                    Name: name,
                    Specification: specification,
                    Number: number,
                    StandardPurchasePrice: standardPurchasePrice,
                    PurchaseAmount: purchaseAmount,
                    TaxAmount: taxAmount,
                    Cost: cost,
                    UnitCost: unitCost,
                    PurchaseCode: purchaseCode,
                    Remark: remark
                }
            });
            $('#selectedStocksForPurchaseReturn').datagrid('selectRow', index);
            $('#selectedStocksForPurchaseReturn').datagrid('beginEdit', index);

            var ed = $('#selectedStocksForPurchaseReturn').datagrid('getEditors', index);
            for (var i = 0; i < ed.length; i++) {
                var e = ed[i];
                if (e.field == "Number") {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function () {
                        $('#selectedStocksForPurchaseReturn').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function () {
                        var number = $(this).val();
                        var currentIndex = $(this).attr("selectedStockRowIndex");
                        var currentRow = $('#selectedStocksForPurchaseReturn').datagrid('getSelected');
                        var taxRate = $("#taxRate").val() != '' ? $("#taxRate").val() : 0;
                        var rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "PurchaseAmount") {
                                $(this).find("div").html(number * currentRow.StandardPurchasePrice);
                            }
                            if ($(this).attr("field") == "TaxAmount") {
                                $(this).find("div").html(parseFloat((number * currentRow.StandardPurchasePrice) * (1 - (100 / (parseFloat(taxRate) + 100)))).toFixed(2));
                            }
                            if ($(this).attr("field") == "Cost") {
                                $(this).find("div").html(parseFloat((number * currentRow.StandardPurchasePrice) * (100 / (parseFloat(taxRate) + 100))).toFixed(2));
                            }
                            if ($(this).attr("field") == "UnitCost") {
                                $(this).find("div").html(parseFloat(currentRow.StandardPurchasePrice * (100 / (parseFloat(taxRate) + 100))).toFixed(2));
                            }
                        });
                        $('#selectedStocksForPurchaseReturn').datagrid('unselectRow', currentIndex);
                        currentRow.Number = number;
                    })
                }
            }
        }

        $("form[action^='/purchasereturn/add']").submit(function () {
            var rows = $('#selectedStocksForPurchaseReturn').datagrid('getRows');
            stockInOutDetailsForPurchaseReturn = "[";
            for (var i = 0; i < rows.length; i++) {
                if (i == (rows.length - 1)) {
                    stockInOutDetailsForPurchaseReturn = stockInOutDetailsForPurchaseReturn + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, \"Number\" : " + rows[i].Number + ", \"UnitCost\" : " + rows[i].StandardPurchasePrice + ", \"Description\" : \"" + rows[i].PurchaseCode + "\" }";
                }
                else {
                    stockInOutDetailsForPurchaseReturn = stockInOutDetailsForPurchaseReturn + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, \"Number\" : " + rows[i].Number + ", \"UnitCost\" : " + rows[i].StandardPurchasePrice + ", \"Description\" : \"" + rows[i].PurchaseCode + "\" }" + ",";
                }
            }
            stockInOutDetailsForPurchaseReturn = stockInOutDetailsForPurchaseReturn + "]";
            $("#stockInOutDetailsForPurchaseReturn").val(stockInOutDetailsForPurchaseReturn);
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (data) {
                    alert(data.Messages[0]);
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#searchStockFromPurchase").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#stocksFromPurchase').datagrid({
                            columns: [[
                                { field: 'IsSelected', title: '选择', width: 60, checkbox: true },
                                { field: 'ReturnNumber', title: '退货数量', width: 80, editor: 'numberbox' },
                                { field: 'ReturnAmount', title: '退货金额', width: 60 },
                                { field: 'InDate', title: '采购日期', width: 80 },
                                { field: 'PurchaseCode', title: '采购单号', width: 80 },
                                { field: 'Name', title: '存货或服务', width: 60 },
                                { field: 'Number', title: '数量', width: 100 },
                                { field: 'UnitCost', title: '单价', width: 80 },
                                { field: 'Amount', title: '金额', width: 80 }
                            ]],
                            data: result
                        });
                        $("#purchases").val(result.Purchases);
                        var purchases = JSON.parse(result.Purchases);
                        var d = new Date();
                        $("#returnDate").val(d.toLocaleDateString().replace('年', '-').replace('月', '-').replace('日', ''));
                        $("#employeeCode").val(purchases[0].EmployeeCode);
                        $("#supplierCode").val(purchases[0].SupplierCode);
                        $("#supplierInvoiceNumber").val(purchases[0].SupplierInvoiceNumber);
                        $("#currency").val(purchases[0].Currency);
                        $("#currencyRate").val(purchases[0].CurrencyRate);
                        $("#wareHouseCode").val(purchases[0].WareHouseCode);
                        $("#contact").val(purchases[0].Contact);
                        $("#contactTelephone").val(purchases[0].ContactTelephone);
                        $("#taxRate").val(purchases[0].TaxRate);
                        $("#remark").val(purchases[0].Remark);

                        var rows = $('#stocksFromPurchase').datagrid('getRows');
                        for (var i = 0; i < rows.length; i++) {
                            $('#stocksFromPurchase').datagrid('beginEdit', i);
                            var ed = $('#stocksFromPurchase').datagrid('getEditors', i);
                            for (var j = 0; j < ed.length; j++) {
                                var e = ed[j];
                                if (e.field == "ReturnNumber") {
                                    $(e.target).attr("selectedStockRowIndex", i);
                                    $(e.target).bind("click", function () {
                                        $('#stocksFromPurchase').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                                    });
                                    $(e.target).bind("blur", function () {
                                        var number = $(this).val();
                                        var currentIndex = $(this).attr("selectedStockRowIndex");
                                        var currentRow = $('#stocksFromPurchase').datagrid('getSelections')[currentIndex];
                                        var rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                                        $("#" + rowId).find("td").each(function () {
                                            if ($(this).attr("field") == "ReturnAmount") {
                                                $(this).find("div").html(number * currentRow.UnitCost);
                                            }
                                        });
                                    })
                                }
                            }
                        }
                    }
                    else {
                        $('#stocksFromPurchase').datagrid('loadData', { total: 0, rows: [] });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#supplierCodeForPurchaseReturn").bind("click", function () {
            InitSelectSupplier('suppliersForPurchaseReturn');
            openWindow("selectSupplierWindowForPurchaseReturn");
        });

        $("#searchSupplierForPurchaseReturn").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#suppliersForPurchaseReturn').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectSupplierForPurchaseReturn").bind("click", function () {
            var currentRow = $('#suppliersForPurchaseReturn').datagrid('getSelected');
            $("#supplierCodeForPurchaseReturn").val(currentRow.Id);
            $("#supplierNameForPurchaseReturn").val(currentRow.Name);
            closeWindow("selectSupplierWindowForPurchaseReturn");
        });

        $("#wareHouseAddressForPurchaseReturn").bind("click", function () {
            InitSelectWareHouse('wareHousesForPurchaseReturn');
            openWindow("selectWareHouseWindowForPurchaseReturn");
        });

        $("#searchWareHouseForPurchaseReturn").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#wareHousesForPurchaseReturn').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectWareHouseForPurchaseReturn").bind("click", function () {
            var currentRow = $('#wareHousesForPurchaseReturn').datagrid('getSelected');
            $("#wareHouseCodeForPurchaseReturn").val(currentRow.Id);
            $("#wareHouseAddressForPurchaseReturn").val(currentRow.Address);
            closeWindow("selectWareHouseWindowForPurchaseReturn");
        });

        $("#purchaseEmployeeCodeForPurchaseReturn").bind("click", function () {
            InitSelectEmployee('employeesForPurchaseReturn');
            openWindow("selectEmployeeWindowForPurchaseReturn");
        });

        $("#searchEmployeeForPurchaseReturn").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#employeesForPurchaseReturn').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectEmployeeForPurchaseReturn").bind("click", function () {
            var currentRow = $('#employeesForPurchaseReturn').datagrid('getSelected');
            $("#purchaseEmployeeCodeForPurchaseReturn").val(currentRow.Id);
            $("#purchaseEmployeeNameForPurchaseReturn").val(currentRow.Name);
            closeWindow("selectEmployeeWindowForPurchaseReturn");
        });
    });
</script>
